package com.puboot.module.controller;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.puboot.common.util.*;
import com.puboot.component.Json2ClassConvert;
import com.puboot.module.model.*;
import com.puboot.module.service.*;
import com.puboot.module.vo.*;
import com.puboot.module.vo.base.ResponseVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * 给前台页面提供的接口，包括针对文章进行的添加评论、获取评论、增加浏览次数和点赞操作
 *
 * @author Linzhaoguan
 * @version V1.0
 * @date 2019年9月11日
 */
@Slf4j
@RestController
@RequestMapping("deal")
@AllArgsConstructor
public class DealController {

    private static final String API = "http://192.168.102.128:5555/api";
    private static final String rootPath = "/workspace/data/image";
    private static final String logPath = "./log.txt";
    private final LkComicService comicService;
    private final LkChapterService chapterService;
    private final LkComicLangService comicLangService;
    private final LkChapterLangService chapterLangService;
    private final ReentrantLock lock = new ReentrantLock();

    @GetMapping("/move")
    @ResponseBody
    public ResponseVo move(HttpServletRequest request, Integer d){
        if (!lock.tryLock()) {
            return ResultUtil.error("only once");
        }
        String from,to;
        if(d==1){
            from = "/workspace/image/";
            to = "/workspace/comic/image/";
        }else{
            from = "/workspace/comic/image/";
            to = "/workspace/image/";
        }
        int loopCount = 8;
        ExecutorService executorService = Executors.newFixedThreadPool(loopCount);

        List<LkComic> comics = comicService.list();
        for(LkComic comic : comics) {
            executorService.execute(() -> {
                List<LkChapter> list = chapterService.list(Wrappers.<LkChapter>lambdaQuery().eq(LkChapter::getComicId, comic.getId()));
                for (LkChapter chapter : list) {
                    String toPath = to+comic.getId()+"/"+chapter.getId();
                    String fromPath = from+comic.getId()+"/"+chapter.getId();
                    File directory = new File(toPath);
                    if (chapter.getContent() == null) continue;
                    String[] imgs = chapter.getContent().split(",");
                    for (int i = 0; i < imgs.length; i++) {
                        if (imgs[i].contains("manimg24.com") || imgs[i].contains("harimanga.com")) {
                            String extName = StringUtils.getFilenameExtension(imgs[i]);
                            if(extName == null) continue;
                            if (!extName.equals("webp")) {
                                directory.mkdirs();
                                String src = fromPath+"/"+i+".webp";
                                String des = toPath+"/"+i+".webp";
                                moveFile(src,des);
                            }
                        }
                    }
                }
            });
        }
        executorService.shutdown();
        while (!executorService.isTerminated()) {
        }
        System.out.println("=======Success======");
        lock.unlock();
        return ResultUtil.success("ok");
    }
    private boolean moveFile(String sourcePath, String destinationPath) {
        Path source = Paths.get(sourcePath);
        Path destination = Paths.get(destinationPath);
        try {
            Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
            return true;
        } catch (IOException e) {
            fileLog(e.getMessage()+"|"+Files.exists(source));
            return false;
        }
    }

    @GetMapping("/down")
    @ResponseBody
    public ResponseVo down(HttpServletRequest request, Integer from, Integer to){
        if (!lock.tryLock()) {
            return ResultUtil.error("only once");
        }
        int loopCount = 64;
        ExecutorService executorService = Executors.newFixedThreadPool(loopCount);
        List<LkComic> list = comicService.limitTotal(from,to);
        for(LkComic comic:list){
            if(comic.getTotal()==1) continue;
            List<LkChapter> chapters = chapterService.list(Wrappers.<LkChapter>lambdaQuery().eq(LkChapter::getComicId, comic.getId()));
            boolean total=true;
            for(LkChapter chapter:chapters){
                if(chapter.getTotal()) continue;
                if(chapter.getContent() == null) continue;
                total = false;
                executorService.execute(() -> {
                    downloadChapter(chapter, 1);
                });
            }
            if(total) comicService.updateTotal(comic.getId());
        }
        executorService.shutdown();
        while (!executorService.isTerminated()) {
        }
        System.out.println("=======Success======");
        lock.unlock();
        return ResultUtil.success("ok");
    }

    @GetMapping("/loss")
    @ResponseBody
    public ResponseVo paddleOCR(HttpServletRequest request) {
        if (!lock.tryLock()) {
            return ResultUtil.error("only once");
        }
        String filePath = "/Users/leonidax/Downloads/down.log"; // 文件路径
        //合并完后只有一个单词或者没有空格的，忽略掉
        String word1="manga", word2=".com", word3="nanga", word4="http";
        List<String> list = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String finalLine = line;
                String[] data = finalLine.split("/");
                String chapterId = data[2];
                if(list.contains(chapterId)) continue;
                list.add(chapterId);
                LkChapter chapter = chapterService.getById(chapterId);

                if(chapter.getContent() == null || chapter.getContent().trim().equals("")){
                    continue;
                }
                List<PaddleVO> results = requestPaddleServer(chapter.getComicId(), chapter.getId(), chapter.getContent());
                if (results == null || results.isEmpty()) {
                    continue;
                }
                log.info("thread.start....");
                new Thread(() -> {
                    List<ImageRecVo> recVos = new ArrayList<>();
                    List<ImageDetVo> detVos = new ArrayList<>();
                    for (PaddleVO image : results) {
                        if (image == null) {
                            recVos.add(null);
                            detVos.add(null);
                            continue;
                        }
                        List<ImageBlockRecVo> blockRecVos = new ArrayList<>();
                        List<ImageBlockDetVo> blockDetVos = new ArrayList<>();
                        List<ImageVBlockDetVo> vBlockDetVos = new ArrayList<>();
                        ImageSizeVo sizeVo = new ImageSizeVo();
                        sizeVo.setW(image.getSize().get(0));
                        sizeVo.setH(image.getSize().get(1));
                        int blockSize = image.getDet().size();
                        for (int i = 0; i < blockSize; i++) {
                            //组装识别文字
                            String words = image.getRec().get(i).get(0);
                            //过滤# & $
                            if(words.contains("#") || words.contains("&") || words.contains("$") || words.contains("/")){
                                continue;
                            }
                            //过滤掉纯英文数字，LOGO等
                            if(org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word1, Locale.ENGLISH) || org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word2, Locale.ENGLISH) || org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word3, Locale.ENGLISH) || org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word4, Locale.ENGLISH)){
                                continue;
                            }
                            ImageBlockRecVo blockRec = new ImageBlockRecVo();
                            blockRec.setW(words);
                            double d = Double.parseDouble(image.getRec().get(i).get(1));
                            int r = (int) (d * 100);
                            blockRec.setR(r);
                            //组装检测区域
                            ImageBlockDetVo blockDet = new ImageBlockDetVo();
                            int minX = image.getDet().get(i).get(0).get(0) < image.getDet().get(i).get(3).get(0) ? image.getDet().get(i).get(0).get(0) : image.getDet().get(i).get(3).get(0);
                            int maxX = image.getDet().get(i).get(1).get(0) > image.getDet().get(i).get(2).get(0) ? image.getDet().get(i).get(1).get(0) : image.getDet().get(i).get(2).get(0);
                            int minY = image.getDet().get(i).get(0).get(1) < image.getDet().get(i).get(1).get(1) ? image.getDet().get(i).get(0).get(1) : image.getDet().get(i).get(1).get(1);
                            int maxY = image.getDet().get(i).get(2).get(1) > image.getDet().get(i).get(3).get(1) ? image.getDet().get(i).get(2).get(1) : image.getDet().get(i).get(3).get(1);
                            float w2 = Math.abs(image.getDet().get(i).get(0).get(0)-image.getDet().get(i).get(1).get(0));
                            float h2 = Math.abs(image.getDet().get(i).get(0).get(1)-image.getDet().get(i).get(1).get(1));
                            if(w2 > h2 && h2/w2>0.19f){
                                continue;
                            }
                            if(w2 < h2 && w2/h2>0.19f){
                                continue;
                            }
                            float w3 = Math.abs(image.getDet().get(i).get(0).get(0)-image.getDet().get(i).get(3).get(0));
                            float h3 = Math.abs(image.getDet().get(i).get(0).get(1)-image.getDet().get(i).get(3).get(1));
                            if(w3 > h3 && h3/w3>0.19f){
                                continue;
                            }
                            if(w3 < h3 && w3/h3>0.19f){
                                continue;
                            }
                            //排除掉竖向英文
                            int w = maxX-minX, h = maxY-minY;
                            //3个字符的情况下，高度比宽度还长，PASS掉
                            if(h>w && words.length()>3) continue;
                            blockDet.setX(minX);
                            blockDet.setY(minY);
                            blockDet.setW(maxX - minX);
                            blockDet.setH(maxY - minY);
                            ImageVBlockDetVo vBlock = new ImageVBlockDetVo(blockDet, blockRec);
                            vBlockDetVos.add(vBlock);
                        }
                        if (vBlockDetVos.isEmpty()) {
                            recVos.add(null);
                            detVos.add(null);
                            continue;
                        }
                        mergeAll(vBlockDetVos, blockRecVos, blockDetVos);
                        //每张图片的识别
                        ImageRecVo recVo = new ImageRecVo();
                        recVo.setL(blockRecVos);
                        recVos.add(recVo);
                        //每张图片的检测
                        ImageDetVo detVo = new ImageDetVo();
                        detVo.setL(blockDetVos);
                        detVo.setS(sizeVo);
                        detVos.add(detVo);
                    }
                    //if(!have) return;
                    chapter.setPosition(Json2ClassConvert.list2Json(detVos));
                    chapter.setDialog(Json2ClassConvert.list2Json(recVos));
                    chapter.setIsFee(true);
                    //fanyi
                    chapterService.translateChapter(chapter.getId(),recVos,detVos);
                    chapter.setChapterId(1);
                    chapterService.update(chapter);
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("=======Success======");

        lock.unlock();
        try{
            log.info("等待3分钟，待Thread子线程结束");
            Thread.sleep(600000);
            System.out.println("=======Success======");
        }catch (InterruptedException e){}

        return ResultUtil.success("ok");
    }

    @GetMapping("/ocr")
    @ResponseBody
    public ResponseVo paddleOCR(HttpServletRequest request, Integer from, Integer to, Integer count) {
        if (!lock.tryLock()) {
            return ResultUtil.error("only once");
        }
        if(from <90) return ResultUtil.error("from:0");
        //合并完后只有一个单词或者没有空格的，忽略掉
        String word1="manga", word2=".com", word3="nanga", word4="http";
        int loopCount = count;
        ExecutorService executorService = Executors.newFixedThreadPool(loopCount);
        List<LkComic> comics = comicService.limitTotal(from, to);
        for(LkComic comic : comics){
            if(comic.getIsFee()) continue;
            List<LkChapter> chapters = chapterService.list(Wrappers.<LkChapter>lambdaQuery().eq(LkChapter::getComicId, comic.getId()));

            final int total = chapters.size();
            AtomicInteger isFee = new AtomicInteger();
            for(LkChapter chapter : chapters) {
                if(chapter.getIsFee()){
                    isFee.getAndIncrement();
                    continue;
                }
                executorService.execute(() -> {
                    if(chapter.getContent() == null || chapter.getContent().trim().equals("")){
                        chapter.setIsFee(true);
                        chapterService.updateIsFee(chapter.getId());
                        return;
                    }
                    List<PaddleVO> results = requestPaddleServer(chapter.getComicId(), chapter.getId(), chapter.getContent());
                    if (results == null || results.isEmpty()) {
                        return;
                    }
                    log.info("thread.start....");
                    new Thread(() -> {
                        boolean have = false;
                        List<ImageRecVo> recVos = new ArrayList<>();
                        List<ImageDetVo> detVos = new ArrayList<>();
                        for (PaddleVO image : results) {
                            if (image == null) {
                                recVos.add(null);
                                detVos.add(null);
                                continue;
                            }
                            have = true;
                            List<ImageBlockRecVo> blockRecVos = new ArrayList<>();
                            List<ImageBlockDetVo> blockDetVos = new ArrayList<>();
                            List<ImageVBlockDetVo> vBlockDetVos = new ArrayList<>();
                            ImageSizeVo sizeVo = new ImageSizeVo();
                            sizeVo.setW(image.getSize().get(0));
                            sizeVo.setH(image.getSize().get(1));
                            int blockSize = image.getDet().size();
                            for (int i = 0; i < blockSize; i++) {
                                //组装识别文字
                                String words = image.getRec().get(i).get(0);
                                //过滤# & $
                                if(words.contains("#") || words.contains("&") || words.contains("$") || words.contains("/")){
                                    continue;
                                }
                                //过滤掉纯英文数字，LOGO等
                                if(org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word1, Locale.ENGLISH) || org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word2, Locale.ENGLISH) || org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word3, Locale.ENGLISH) || org.thymeleaf.util.StringUtils.containsIgnoreCase(words, word4, Locale.ENGLISH)){
                                    continue;
                                }
                                ImageBlockRecVo blockRec = new ImageBlockRecVo();
                                blockRec.setW(words);
                                double d = Double.parseDouble(image.getRec().get(i).get(1));
                                int r = (int) (d * 100);
                                blockRec.setR(r);
                                //组装检测区域
                                ImageBlockDetVo blockDet = new ImageBlockDetVo();
                                int minX = image.getDet().get(i).get(0).get(0) < image.getDet().get(i).get(3).get(0) ? image.getDet().get(i).get(0).get(0) : image.getDet().get(i).get(3).get(0);
                                int maxX = image.getDet().get(i).get(1).get(0) > image.getDet().get(i).get(2).get(0) ? image.getDet().get(i).get(1).get(0) : image.getDet().get(i).get(2).get(0);
                                int minY = image.getDet().get(i).get(0).get(1) < image.getDet().get(i).get(1).get(1) ? image.getDet().get(i).get(0).get(1) : image.getDet().get(i).get(1).get(1);
                                int maxY = image.getDet().get(i).get(2).get(1) > image.getDet().get(i).get(3).get(1) ? image.getDet().get(i).get(2).get(1) : image.getDet().get(i).get(3).get(1);
                                float w2 = Math.abs(image.getDet().get(i).get(0).get(0)-image.getDet().get(i).get(1).get(0));
                                float h2 = Math.abs(image.getDet().get(i).get(0).get(1)-image.getDet().get(i).get(1).get(1));
                                if(w2 > h2 && h2/w2>0.19f){
                                    continue;
                                }
                                if(w2 < h2 && w2/h2>0.19f){
                                    continue;
                                }
                                float w3 = Math.abs(image.getDet().get(i).get(0).get(0)-image.getDet().get(i).get(3).get(0));
                                float h3 = Math.abs(image.getDet().get(i).get(0).get(1)-image.getDet().get(i).get(3).get(1));
                                if(w3 > h3 && h3/w3>0.19f){
                                    continue;
                                }
                                if(w3 < h3 && w3/h3>0.19f){
                                    continue;
                                }
                                //排除掉竖向英文
                                int w = maxX-minX, h = maxY-minY;
                                //3个字符的情况下，高度比宽度还长，PASS掉
                                if(h>w && words.length()>3) continue;
                                blockDet.setX(minX);
                                blockDet.setY(minY);
                                blockDet.setW(maxX - minX);
                                blockDet.setH(maxY - minY);
                                ImageVBlockDetVo vBlock = new ImageVBlockDetVo(blockDet, blockRec);
                                vBlockDetVos.add(vBlock);
                            }
                            if (vBlockDetVos.isEmpty()) {
                                recVos.add(null);
                                detVos.add(null);
                                continue;
                            }
                            mergeAll(vBlockDetVos, blockRecVos, blockDetVos);
                            //每张图片的识别
                            ImageRecVo recVo = new ImageRecVo();
                            recVo.setL(blockRecVos);
                            recVos.add(recVo);
                            //每张图片的检测
                            ImageDetVo detVo = new ImageDetVo();
                            detVo.setL(blockDetVos);
                            detVo.setS(sizeVo);
                            detVos.add(detVo);
                        }
                        //if(!have) return;
                        chapter.setPosition(Json2ClassConvert.list2Json(detVos));
                        chapter.setDialog(Json2ClassConvert.list2Json(recVos));
                        chapter.setIsFee(true);
                        isFee.getAndIncrement();
                        //fanyi
                        chapterService.translateChapter(chapter.getId(),recVos,detVos);
                        chapter.setChapterId(1);
                        chapterService.update(chapter);

                        if(isFee.get() == total){
                            comicService.updateIsFee(chapter.getComicId());
                        }
                    }).start();
                });
            }
            if(isFee.get() == total){
                comicService.updateIsFee(comic.getId());
            }
        }
        executorService.shutdown();
        while (!executorService.isTerminated()) {
        }

        lock.unlock();
        try{
            log.info("等待3分钟，待Thread子线程结束");
            Thread.sleep(180000);
            System.out.println("=======Success======");
        }catch (InterruptedException e){}

        return ResultUtil.success("ok");
    }

    private List<PaddleVO> requestPaddleServer(Integer comic, Integer id, String content){
        String[] items = content.split(",");

        String url = API+"?id="+id+"&comic="+comic+"&size="+items.length;
        RestTemplate restTemplate = new RestTemplate();
        //log.info("URL:{}",url);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36");
        headers.set("Accept", "*/*");
        headers.set("Host", "www.idmzj.com");
        headers.set("Connection", "keep-alive");

        // 封装请求
        HttpEntity<String> requestEntity = new HttpEntity<>(null, headers);
        try {
            // 发送POST请求并自动将响应体解析为Map
            //ResponseEntity<String> t = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            //log.info("Response:{}",t.getBody());
            ResponseEntity<PaddleVO[]> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, PaddleVO[].class);
            // 从Map中提取result字段
            List<PaddleVO> list = Arrays.asList(response.getBody());
            return list;
        }catch (Exception e){
            System.out.println(id);
            e.printStackTrace();
            return null;
        }
    }

    private void mergeAll(List<ImageVBlockDetVo> vBlockList, List<ImageBlockRecVo> blockRecVos, List<ImageBlockDetVo> blockDetVos){
        List<ImageVBlockDetVo> newList = new ArrayList<>();
        List<ImageVBlockDetVo> endList = new ArrayList<>();
        ImageVBlockDetVo first = vBlockList.get(0);
        first = mergeFirst(first, vBlockList, newList);
        endList.add(first);
        while(newList.size()>0){
            List<ImageVBlockDetVo> new2List = new ArrayList<>();
            ImageVBlockDetVo baseVo = newList.get(0);
            baseVo = mergeFirst(baseVo, newList, new2List);
            endList.add(baseVo);
            newList = new2List;
        }
        for(ImageVBlockDetVo vo : endList){
            ImageBlockRecVo rec = new ImageBlockRecVo();
            ImageBlockDetVo det = new ImageBlockDetVo();

            rec.setF(0);//calculateFontSize(vo.getWords(),vo.getW(),vo.getH()));
            String words = vo.getWords();
            if(words.length()<5) continue;
            rec.setW(vo.getWords());
            rec.setR(vo.getRate());
            blockRecVos.add(rec);

            det.setX(vo.getX());
            det.setY(vo.getY());
            det.setW(vo.getW());
            det.setH(vo.getH());
            blockDetVos.add(det);
        }
    }

    /**
     * 计算出第一个block拼凑后的block
     * @param first
     * @param oldList
     * @param newList
     */
    private ImageVBlockDetVo mergeFirst(ImageVBlockDetVo first, List<ImageVBlockDetVo> oldList ,List<ImageVBlockDetVo> newList){
        ImageVBlockDetVo block = first;
        for(int i=1; i<oldList.size(); i++){
            ImageVBlockDetVo vBlock = oldList.get(i);
            if(vBlock.getY() > (block.getY1()+block.getH1())){
                newList.addAll(oldList.subList(i,oldList.size()));
                //System.out.println("End Merge :"+block.getWords());
                return block;
            }
            if(isMerge(block, vBlock)){
                //System.out.println("Found :"+vBlock.getWords());
                block = merge(block, vBlock);
                ListIterator<ImageVBlockDetVo> listIterator = newList.listIterator();
                while (listIterator.hasNext()) {
                    ImageVBlockDetVo vo = listIterator.next();
                    if(isMerge(block, vo)){
                        //System.out.println("Found2 :"+vo.getWords());
                        block = merge(block, vo);
                        listIterator.remove();
                    }
                }
            }else{
                //System.out.println("Not Found :"+vBlock.getWords());
                newList.add(vBlock);
            }
        }
        //System.out.println("Finish Merge :"+block.getWords());
        return block;
    }
    private ImageVBlockDetVo merge(ImageVBlockDetVo v1, ImageVBlockDetVo v2){
        if(v2.getWords().length()==1) return v1;
        ImageVBlockDetVo vo = new ImageVBlockDetVo();
        //合并真实区域
        vo.setX(v1.getX()<v2.getX() ? v1.getX() : v2.getX());
        vo.setY(v1.getY()<v2.getY() ? v1.getY() : v2.getY());
        int w1 = v1.getX()+v1.getW(), w2 = v2.getX()+v2.getW();
        vo.setW(w1<w2 ? w2-vo.getX() : w1-vo.getX());
        int h1 = v1.getY()+v1.getH(), h2 = v2.getY()+v2.getH();
        vo.setH(h1<h2 ? h2-vo.getY() : h1-vo.getY());
        //合并虚拟区域
        vo.setX1(v1.getX1()<v2.getX1() ? v1.getX1() : v2.getX1());
        vo.setY1(v1.getY1()<v2.getY1() ? v1.getY1() : v2.getY1());
        w1 = v1.getX1()+v1.getW1(); w2 = v2.getX1()+v2.getW1();
        vo.setW1(w1<w2 ? w2-vo.getX1() : w1-vo.getX1());
        h1 = v1.getY1()+v1.getH1(); h2 = v2.getY1()+v2.getH1();
        vo.setH1(h1<h2 ? h2-vo.getY1() : h1-vo.getY1());

        //合并文字
        vo.setWords(v1.getWords()+" "+v2.getWords());
        vo.setRate(v1.getRate()<v2.getRate() ? v1.getRate() : v2.getRate());

        return vo;
    }
    /**
     * 判断两个矩形是否有交集
     * @param v1
     * @param v2
     * @return
     */
    private boolean isMerge(ImageVBlockDetVo v1, ImageVBlockDetVo v2){
        int x1 = v1.getX1(), x2 = v2.getX1(), y1 = v1.getY1(), y2 = v2.getY1();
        int w1 = x1+v1.getW1(),w2 = x2+v2.getW1(),h1 = y1+v1.getH1(),h2 = y2+v2.getH1();
        if(h2<y1 || y2>h1 || w2<x1 || w1<x2)
            return false;
        else
            return true;
    }


    private void downloadChapter(LkChapter chapter, int time){
        String content = chapter.getContent();
        if(content == null || content.equals("")) return;
        List<String> images = Arrays.stream(chapter.getContent().split(",")).collect(Collectors.toList());
        boolean success = true;
        for(int i=0; i<images.size(); i++){
            boolean t = downloadImage(rootPath+"/"+chapter.getComicId()+"/"+chapter.getId(),images.get(i),i);
            if(!t) success = false;
        }
        if(success){
            chapter.setTotal(true);
            chapterService.updateTotal(chapter.getId());
        }else{
            if(time==3) return;
            time++;
            downloadChapter(chapter, time);
        }
    }

    private boolean downloadImage(String dir, String imageUrl, int i) {
        String fileName;
        if(i==-1){
            fileName = StringUtils.getFilename(imageUrl);
        }else{
            String extName = StringUtils.getFilenameExtension(imageUrl);
            fileName = ""+i+"."+extName;
        }
        if (fileName == null || fileName.isEmpty()) {
            return false;
        }

        // 构建保存路径
        File saveDirectory = new File(dir);
        if (!saveDirectory.exists()) {
            saveDirectory.mkdirs();
        }
        File file = new File(saveDirectory, fileName);
        if(file.exists()) return true;

        // 下载图片并保存
        try{
            // 设置连接和请求头
            URL url = new URL(imageUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // 模拟浏览器请求
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(90000);
            connection.setReadTimeout(90000);
            InputStream in = connection.getInputStream();
            FileOutputStream out = new FileOutputStream(file);
            byte[] buffer = new byte[1024000];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            connection.disconnect();
            System.out.println("图片已保存到: " + file.getAbsolutePath());
        }
        catch (java.io.FileNotFoundException e404){
            file.delete();
            log.info("downE404:{}",imageUrl);
            return true;
        }
        catch (Exception e){
            file.delete();
            log.info("downE:{}",imageUrl);
            return false;
        }
        return true;
    }

    private void fileLog(String text){
        File file = new File(logPath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter writer = new FileWriter(file, true);
            writer.write(text);
            writer.write("\n");
            writer.close();
        } catch (IOException e) {
        }
    }

}
